//
//  ZyaFeedOrderDetailController.swift
//  SlaughterClient
//
//  Created by Zhouweibin on 2018/1/27.
//  Copyright © 2018年 zwb. All rights reserved.
//

import UIKit

class ZyaFeedOrderDetailController: UIViewController {

    var order = [ZyaFeedOrder]()
    var address = [ZyaClientAddress]()
    var isUpdateOrder = false

    override func viewDidLoad() {
        super.viewDidLoad()

        setupSubviews()
        
        KSNetwork.shared.doRequest(API.queryClientAddress(k_addr_type: "")) { (data: BaseResult<ZyaClientAddress>) in
            if let infos = data.infoArrCombine {
                self.address = infos
                let currMark = infos.filter{ $0.currMark == 1 }.first
                if let one = currMark?.clientAdd {
                    self.addressL.text = one
                } else {
                    self.addressL.text = infos.first?.clientAdd ?? ""
                }
            }
           
            
        }
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "新增地址", style: .done, target: self, action: #selector(addAddress))
    }
    
    @objc func addAddress() {
        let vc = ZyaClientAddressDetailController()
        vc.title = "新增地址"
        vc.newAddClientHandler = { [weak self] clientStr in
            let data = ZyaClientAddress(JSON: ["client_add" : ""])
            
            data?.clientAdd = clientStr
            self?.address.append(data!)
            self?.addressL.text = clientStr
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @objc func useAcvanceAction() {
        useAdvance.isSelected = !useAdvance.isSelected
    }
    private func setupSubviews() {
        
        title = "商品详情"
        edgesForExtendedLayout = UIRectEdge()
        
        view.backgroundColor = UIColor.white
        view.addSubview(scrollView)
        scrollView.addSubview(dateLabel)
        scrollView.addSubview(dateTf)
        scrollView.addSubview(markLabel)
        scrollView.addSubview(markTv)
        scrollView.addSubview(addressLabel)
        scrollView.addSubview(addressL)
        scrollView.addSubview(selectAddressButton)
        scrollView.addSubview(useAdvanceLabel)
        scrollView.addSubview(useAdvance)
        useAdvance.addTarget(self, action: #selector(useAcvanceAction), for: .touchUpInside)

        view.addSubview(tools)
 
        dateTf.delegate = self
        tools.delegate = self
        dateTf.text = Date().today("yyyy-MM-dd")
        selectAddressButton.addTarget(self, action: #selector(selectAddressAction), for: .touchUpInside)
        
        scrollView.snp.makeConstraints { (maker) in
            maker.edges.equalToSuperview()
        }
        
        dateLabel.snp.makeConstraints { (maker) in
            maker.left.equalTo(8)
            maker.top.equalTo(24)
            maker.width.equalTo(90)
        }
        
        dateTf.snp.makeConstraints { (maker) in
            maker.left.equalTo(dateLabel.snp.right)
            maker.height.equalTo(44)
            maker.right.equalTo(-8)
            maker.centerY.equalTo(dateLabel)
        }

        markLabel.snp.makeConstraints { (maker) in
            maker.top.equalTo(dateTf.snp.bottom).offset(12)
            maker.left.equalTo(8)
        }
        
        markTv.snp.makeConstraints { (maker) in
            maker.top.equalTo(markLabel.snp.bottom).offset(12)
            maker.left.equalTo(8)
            maker.right.equalTo(-8)
            maker.height.equalTo(90)
        }
      
        addressLabel.snp.makeConstraints { (maker) in
            maker.top.equalTo(markTv.snp.bottom).offset(12)
            maker.left.equalTo(8)
        }
        
        addressL.snp.makeConstraints { (maker) in
            maker.left.equalTo(8)
            maker.right.equalTo(-48)
            maker.height.equalTo(44)
            maker.top.equalTo(addressLabel.snp.bottom).offset(12)
        }
        
        selectAddressButton.snp.makeConstraints { (maker) in
            maker.right.equalTo(-8)
            maker.size.equalTo(CGSize(width: 30, height: 30))
            maker.centerY.equalTo(addressL.snp.centerY)
        }
        
        useAdvanceLabel.snp.makeConstraints { (maker) in
            maker.top.equalTo(addressL.snp.bottom).offset(12)
            maker.left.equalTo(8)
        }
        useAdvance.snp.makeConstraints { (maker) in
            maker.centerY.equalTo(useAdvanceLabel)
            maker.left.equalTo(useAdvanceLabel.snp.right).offset(15)
            maker.width.height.equalTo(30)
        }
        
        tools.snp.makeConstraints { (maker) in
            maker.left.right.bottom.equalToSuperview()
            maker.height.equalTo(60)
        }
        
        let line = UIView()
        scrollView.addSubview(line)
        
        line.snp.makeConstraints { (maker) in
            maker.width.left.right.equalToSuperview()
            maker.height.equalTo(1)
            maker.top.equalTo(addressL.snp.bottom)
        }
    }
    
    @objc private func selectAddressAction() {
        let selectView = FZSelectView()
        selectView.selectedClosure = { (selectedIndexs, selectedValues) in
            self.addressL.text = selectedIndexs
        }
        
        selectView.itemNames = address.compactMap { $0.clientAdd }
        selectView.itemIDs = address.compactMap { $0.clientAdd }
        selectView.show()
    }
    
    var scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.backgroundColor = Theme.tableViewColor
        sv.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0)
        sv.showsVerticalScrollIndicator = false
        return sv
    }()
    
    lazy var dateLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.textColor
        label.text = "提货时间："
        return label
    } ()
    
    lazy var markLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.textColor
        label.text = "备注："
        return label
    } ()
    
    lazy var addressLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.textColor
        label.text = "收货地址："
        return label
    } ()
    lazy var useAdvanceLabel: UILabel = {
        let label = UILabel()
        label.textColor = Theme.textColor
        label.text = "使用预付款支付："
        return label
    } ()
    lazy var useAdvance: UIButton = {
        let v = UIButton()
        v.setImage(UIImage(named: "unselect"), for: .normal)
        v.setImage(UIImage(named: "select"), for: .selected)
          return v
    } ()

    lazy var dateTf: UITextField = {
        let tf = UITextField()
        tf.layer.borderColor = Theme.primaryLightColor.cgColor
        tf.layer.borderWidth = 1
        tf.layer.cornerRadius = 3
        tf.backgroundColor = UIColor.white
        tf.textAlignment = .center
        return tf
    } ()
    
    lazy var markTv: UITextView = {
        let tf = UITextView()
        tf.layer.borderColor = Theme.primaryLightColor.cgColor
        tf.layer.borderWidth = 1
        tf.layer.cornerRadius = 3
        tf.font = UIFont.systemFont(ofSize: 17)
        return tf
    } ()
    
    lazy var addressL: UITextField = {
        let tf = UITextField()
        tf.layer.borderColor = Theme.primaryLightColor.cgColor
        tf.layer.borderWidth = 1
        tf.layer.cornerRadius = 3
        tf.isUserInteractionEnabled = false
        tf.backgroundColor = UIColor.white
        tf.placeholder = "请选择或者输入地址"
        tf.font = UIFont.boldSystemFont(ofSize: 15)
        tf.textColor = Theme.primaryColor()
        return tf
    } ()
    
    lazy var selectAddressButton: UIButton = {
        let button = UIButton()
        button.setImage(#imageLiteral(resourceName: "bottom"), for: UIControl.State())
        return button
    } ()

    
    lazy var tools: ZyaFeedOrderToolBar = {
        let tools = ZyaFeedOrderToolBar()
        return tools
    } ()
}

extension ZyaFeedOrderDetailController: UITextFieldDelegate {
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        // 选择单时间
        let cvc = LPCalendar()
        cvc.isRadio = true
        cvc.delegate = self
        self.present(cvc, animated: true, completion: nil)
        return false
    }

}

extension ZyaFeedOrderDetailController: LPCalendarDelegate {
    func calendarViewSelectDate(_ date: String?) {
        dateTf.text = date
    }
}

extension ZyaFeedOrderDetailController: ZyaFeedOrderToolBarDelegate {
    
    func selectProduct() {
        
        if let vc = navigationController?.viewControllers[1] {
            navigationController?.popToViewController(vc, animated: true)
        }

    }
    
    func sumbitOrder() {
        
        guard addressL.text != "" else {
            KSToast("请选择地址后保存")
            return
        }
        
        if isUpdateOrder {
            
            let orders = order.map { (item) -> ZyaPurchaseDetail in
                var good = ZyaPurchaseDetail(JSON: ["s_cess_price" : ""])
            
                good?.sGoodsId = item.brandId
                good?.vouId = item.vouId
                good?.idKey = item.idKey
                good?.sAmountZ = item.amount
                good?.sCessPrice = item.brandPrice
                return good!
                }.toJSONString()
            
            let mainDir = [
                "s_client_address": self.addressL.text!,
                "s_orderform_date": Date().today(),
                "s_remark": markTv.text.unwrap,
                "tj_yjrq": dateTf.text.unwrap,
                "id_key": order.first?.vouId ?? "",
                "kf_id": USERINFO.kfId.unwrap,
                "advance_bs":useAdvance.isSelected ? "1" : "0"
                ] as [String : Any]
            
            let mainJosn = dictionaryToJson(mainDir)
            
            KSNetwork.shared.doRequest(API.updateOrders(main: mainJosn, detail: orders!)) { (result: BaseResult<IdKey>) in

                if result.message.unwrap.contains("成功") {
                    KSToast("修改成功")
                    self.navigationController?.popToRootViewController(animated: true)
                } else {
                    KSToast("修改失败")
                }
            }
        } else {
            
            let orders = order.map { (item) -> ZyaFeedDetail in
                let good = ZyaFeedDetail(JSON: ["price" : ""])
                good?.amount = item.amount
                good?.brandSortId = item.brandSortId
                good?.price = item.brandPrice
                good?.sClientAddress = self.addressL.text!
                good?.vouId = item.vouId
                good?.idKey = item.brandId
                good?.orgCode = item.orgCode
                good?.orgName = item.orgName
                good?.sOperationId = item.staffId
                return good!
                }.toJSONString()
       
            KSNetwork.shared.doRequest(API.saveOrders(goods: orders!, thrj: dateTf.text!, memo: markTv.text,advance_bs: useAdvance.isSelected ? "1" : "0")) { (result: BaseResult<IdKey>) in
                
                if result.message.unwrap.contains("成功") {
                    KSToast("保存成功")
                    self.navigationController?.popToRootViewController(animated: true)
                } else {
                    KSToast("保存失败")
                }
            }
        }
    }
}
